<template>
  <div v-show="vMode === 'home'">
    <van-nav-bar title="财务账单" left-text="返回" left-arrow @click-left="goHome" fixed>
      <template #right>
        <van-icon name="ellipsis" size="18" @click="home.toolBtn = true" />
      </template>
    </van-nav-bar>
    <p style="margin-top: 40px"></p>
    <van-list v-model:loading="loading" :finished="finished" finished-text="没有更多了" offset="10" @load="onLoad">
      <!--@todo tab 显示用信息-->
      <van-cell v-for="item in vList" :key="item.id" :label="`${item.date} 最近更新： ${item.mtime}`"
        :value="`${item.inout ? '-' : '+'}${item.money}`" @click="onView(item)" is-link>
        <template #title>
          <span class="custom-title">{{ item.name }}</span>
        </template>
      </van-cell>
    </van-list>
    <van-sticky :offset-bottom="50" style="text-align: right; margin-right: 10px;" position="bottom">
      <van-button type="primary" icon="replay" plain round hairline @click="onResetData"></van-button>
    </van-sticky>
  </div>
  <div v-show="vMode === 'view'">
    <van-nav-bar :title="vRow.name" left-text="返回" left-arrow @click-left="vMode = 'home'">
      <template #right>
        <van-icon name="ellipsis" size="18" @click="home.toolBtn = true" />
      </template>
    </van-nav-bar>
    <van-cell center title="名称" :value="vRow.name" />
    <van-cell center title="日期" :value="vRow.date" />
    <van-cell center title="主体" :value="`${vRow.master_id}${vRow.master ? ' | ' + vRow.master : ''}`" />
    <van-cell center title="金额" :value="vRow.money * vRow.inout" />
    <van-cell center title="客体" :value="vRow.slave" />
    <van-cell center title="城市" :value="vRow.city" />
    <van-cell center title="地址" :value="vRow.address" />
    <van-cell center title="描述" :label="vRow.descrip" />
    <van-cell center title="编辑时间" :value="vRow.mtime" />
    <van-cell center title="创建时间" :value="vRow.ctime" />
    <div style="margin: 16px; text-align: right">
      <van-button round icon="plus" type="primary" size="small" @click="onTplNew"
        style="margin-right: 10px;">模板新增</van-button>
      <van-button round type="primary" size="small" @click="onEdit" style="margin-right: 10px;">修改</van-button>
      <van-button round type="danger" size="small" @click="onDelete">删除</van-button>
    </div>
  </div>
  <div v-show="vMode === 'edit' || vMode === 'tpl-edit'">
    <van-nav-bar :title="vRowEdit.name" left-text="返回" left-arrow @click-left="vMode = 'home'"
      :right-text="`${vRow.id ? '详情' : ''}`" @click-right="vMode = 'view'" />
    <van-form @submit="onSubmit">
      <van-field clickable name="date" v-model="vRowEdit.date" label="日期" @click="vSetting._showDatePicker = true"
        autocomplete="off" clearable required />
      <van-popup v-model:show="vSetting._showDatePicker" position="bottom">
        <van-date-picker type="date" @confirm="onDateConfirm" @cancel="vSetting._showDatePicker = false"
          :min-date="vSetting.minDate" :max-date="vSetting.maxDate" />
      </van-popup>
      <van-field v-model="vRowEdit.name" name="name" label="名称" placeholder="名称" required
        :rules="[{ required: true, message: '请填写名称' }]" clearable />
      <van-field v-model="vRowEdit.master" name="master" label="主体" clearable @blur="onPopup('master', true)" required
        :rules="[{ required: true, message: '请填写主体' }]">
        <template #button>
          <van-button size="small" type="success" plain round @click="onPopup('master')">获取</van-button>
        </template>
      </van-field>
      <van-field v-model="vRowEdit.money" name="money" label="金额" placeholder="金额" required
        :rules="[{ required: true, message: '请填写金额' }]" clearable />
      <van-field v-model="vRowEdit.inout" name="gender" label="类型">
        <template #input>
          <van-radio-group v-model="vRowEdit.inout" direction="horizontal">
            <van-radio name="-1">支出</van-radio>
            <van-radio name="1">收入</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-model="vRowEdit.slave" name="slave" label="客体" clearable @blur="onPopup('slave', true)">
        <template #button>
          <van-button size="small" type="success" plain round @click="onPopup('slave')">获取</van-button>
        </template>
      </van-field>
      <van-field v-model="vRowEdit.city" name="city" label="城市" placeholder="城市" clearable />
      <van-field v-model="vRowEdit.address" name="address" label="地址" placeholder="地址" clearable />
      <van-field v-model="vRowEdit.descrip" name="descrip" rows="2" autosize label="描述" type="textarea"
        placeholder="请输入描述" :rules="[{ required: true, message: '请填写描述' }]" clearable required />
      <!-- 公共 popup -->
      <van-popup v-model:show="vSetting._popup" position="bottom">
        <van-picker :columns="vSetting._popupOption" @confirm="onPopupConfirm" @cancel="vSetting._popup = false" />
      </van-popup>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          {{ editBtnDesc() }}
        </van-button>
      </div>
    </van-form>
  </div>
  <!-- 主页工具栏弹出框 -->
  <van-action-sheet v-model:show="home.toolBtn" :actions="home.tools" cancel-text="取消" close-on-click-action
    @cancel="home.toolBtn = false" @select="onHomeToolSel" />
  <!-- 搜索对话框 -->
  <van-dialog v-model:show="home.search.show" title="账单搜索" show-cancel-button @confirm="onSearch">
    <van-search v-model="home.search.value" placeholder="请输入搜索关键词" @keydown="onSearchKeydown" />
  </van-dialog>
</template>

<script lang="ts" setup>
import {
  showConfirmDialog,
  showFailToast,
  showLoadingToast,
  showSuccessToast,
} from "vant";
import { Wap } from "../../../common/wap";
import { ref, toRaw } from "vue";
import type { Ref } from "vue";
import { useRouter } from "vue-router";

import type {
  PickerOption,
} from 'vant';

//@todo 页面设置，先分年月，再获取子财务
const router = useRouter();

const editInit: KvObj = {
  date: Wap.dateFormat(),
  inout: -1,
};

// 数据定义
const vList: Ref<Array<KvObj>> = ref([]);
const loading = ref(false);
const finished = ref(false);
const vMode = ref("home");
const vRow: Ref<KvObj> = ref({});
const vRowEdit: Ref<KvObj> = ref(editInit);
const home = ref({
  toolBtn: false,
  tools: [
    { name: "搜索", key: "search" },
    { name: "新增", key: "add" },
  ],
  search: {
    value: "",
    show: false,
  },
});
const _popupOption: Array<KvObj> = [];
const vSetting: KvObj = ref({
  _popupOption,
  _popup: false,
  _showDatePicker: false,
  minDate: new Date(2013, 0, 1),
  maxDate: new Date(),
  masterCache: null,
});
const cPg = ref({
  current: 0,
  pageSize: 15,
});

function goHome() {
  router.push({ path: "/finance" });
}

/**
 *
 * @param {object} [postData]
 * @param {boolean} [flushMk]
 */
function loadList(postData?: KvObj | null, flushMk?: boolean) {
  postData = postData || {};
  if (flushMk) {
    cPg.value.current = 1;
  }
  postData = Object.assign({}, cPg.value, postData);
  Wap.post("/square/data/bill", postData)
    .then((result) => {
      if (result.status === "ok") {
        let data = result.data;
        let oData = vList.value;
        if (flushMk) {
          oData = [];
        }
        let list = data.list || [];
        if (!list || list.length === 0) {
          finished.value = true;
          loading.value = false;
        } else {
          loading.value = false;
          finished.value = false;
        }
        list = oData.concat(list);
        vList.value = list;
      } else {
        finished.value = true;
        loading.value = false;
        showFailToast(result.msg);
      }
    })
    .catch((error) => {
      console.log(error);
      finished.value = true;
      loading.value = false;
    });
}

function onLoad() {
  cPg.value.current += 1;
  loadList();
}

function onSearch() {
  let { value } = home.value.search;
  let post = {
    s_keyword: "name",
    s_value: value,
  };
  vMode.value = "home";
  cPg.value = Object.assign({}, cPg.value, post);
  loadList(post, true);
}

function onSearchKeydown(e: any) {
  switch (e.which) {
    case 13:
      home.value.search.show = false;
      onSearch();
      break;
  }
}

// 编辑
function onView(item: KvObj) {
  console.log({ item: toRaw(item) });
  vMode.value = 'view';
  vRow.value = item;
}

// 编辑
function onEdit() {
  vRowEdit.value = vRow.value;
  vMode.value = "edit";
}

// 模板新增
function onTplNew() {
  let rowData = { ...toRaw(vRow.value) }; // object 深度复制产生
  rowData.id = 0;
  rowData.date = Wap.dateFormat();
  vRowEdit.value = rowData;
  vMode.value = "tpl-edit";
}

function onDelete() {
  showConfirmDialog({
    title: "提示",
    message: "您确定要删除数据吗，删除后不可撤销？",
  }).then(() => {
    // on confirm
    let loading = showLoadingToast({
      duration: 0, // 持续展示 toast
      forbidClick: true,
      message: "数据提交中",
    });
    Wap.post("/square/data/bill/del", { id: vRowEdit.value.id })
      .then((result) => {
        Wap.resolveResponse(result)
          .then(() => {
            loadList(null, true);
            showSuccessToast(result.msg);
            vMode.value = "list";
          })
          .catch((msg) => {
            showFailToast(msg);
          });
      })
      .finally(() => {
        loading.close();
      });
  });
}

// 重置数据
function onResetData() {
  cPg.value = { ...cPg.value, ...{ current: 1, s_value: "" } };
  vList.value = [];
  loadList();
}

function onHomeToolSel(item: KvObj) {
  let key = item.key;
  switch (key) {
    case "search":
      home.value.search.show = true;
      break;
    case "add":
      vMode.value = "edit";
      vRow.value = {};
      vRowEdit.value = editInit
      break;
  }
}

function onSubmit(values: KvObj) {
  let saveData = Object.assign({}, vRowEdit.value, values);
  let loading = showLoadingToast({
    duration: 0, // 持续展示 toast
    forbidClick: true,
    message: "数据提交中",
  });
  Wap.post("/square/data/bill/save", saveData)
    .then((result) => {
      Wap.resolveResponse(result)
        .then(() => {
          if (vRow.value.id) {
            vRowEdit.value.money = "";
          }
          showSuccessToast(result.msg);
          loadList(null, true);
        })
        .catch((msg) => {
          showFailToast(msg);
        });
    })
    .finally(() => {
      loading.close();
    });
}
/**
 * 公共的开启 popup 的方法
 * @param {string} key
 * @param {boolean} [require]
 */
function onPopup(key: string, require?: boolean) {
  vSetting.value._popupCurKey = key;
  let url,
    search = "";
  switch (key) {
    case "master":
      if (!vSetting.value.masterCache) {
        url = `/square/data/bill/search/master?is_master=1&search=${search}`;
        Wap.get(url).then((result) => {
          let data = result.data || [];
          let newData: Array<KvObj> = [];
          data.forEach((dd: KvObj) => {
            newData.push({ text: dd.name, value: dd.id });
          });
          vSetting.value._popupOption = newData;
          vSetting.value.masterCache = newData;
          vSetting.value._popup = true;
        });
      } else {
        vSetting.value._popupOption = vSetting.value.masterCache;
        vSetting.value._popup = true;
      }
      break;
    case "slave":
      search = vRowEdit.value.slave;
      if (require && !search) {
        return;
      }
      url = `/square/data/bill/search/master?is_master=0&search=${search}`;
      Wap.get(url).then((result) => {
        let data = result.data || [];
        let newData: Array<KvObj> = [];
        data.forEach((dd: KvObj) => {
          newData.push({ text: dd.name, value: dd.id });
        });
        vSetting.value._popupOption = newData;
        vSetting.value._popup = true;
      });
      break;
  }
}


//确认时处理
function onPopupConfirm(item?: { selectedOptions: Array<PickerOption> }) {
  let selectedOptions = item?.selectedOptions;
  if (!selectedOptions || selectedOptions.length == 0) {
    vSetting.value._popup = false;
    return;
  }
  let options = selectedOptions[0];
  let key = vSetting.value._popupCurKey;
  switch (key) {
    case "master":
      vRowEdit.value.master = options.text;
      vRowEdit.value.master_id = options.value;
      break;
    case "slave":
      vRowEdit.value.slave = options.text;
      vRowEdit.value.slave_id = options.value;
      break;
  }
  vSetting.value._popup = false;
}

function onDateConfirm(time: Date) {
  vRowEdit.value.date = Wap.dateFormat(time);
  vSetting.value._showDatePicker = false;
}

// 编辑保存按钮描述
function editBtnDesc() {
  switch (vMode.value) {
    case "edit":
      if (vRowEdit.value.id) {
        return "修改";
      }
      return "新增";
    case "tpl-edit":
      return "模板新增";
    default:
      return "提交";
  }
}

</script>